#include "mainwindow.h"

#include <QChartView> //添加图表的头文件
#include <QSplineSeries>          //线条类
#include <QTimer>               //时间类
#include <QtMath>
#include <QDateTime>
#include <QDateTimeAxis>        //时间坐标轴类
#include <QValueAxis>           //普通坐标轴类
#include <QTextCodec>
#include <QMessageBox>
#include <QString>
#include <QDebug>
#include <QMessageBox>

//这里使用这个命名空间在下面头文件前，是为了防止 #include <qchartview.h> 添加失败
QT_CHARTS_USE_NAMESPACE

#include "ui_mainwindow.h"



float temp_data; //温度
float humi_data; //湿度
float light_data; //亮度
float soil_data; //土壤
float mq2_data; //mq2气体
float rain_data; //雨量
short light_pwm;//光强

bool relaySw=false;//继电器
bool flag_Sw=false;//网络
bool flag_Send=0;//本机发送标志位
bool Master = true; // 默认设置主机通信
bool run_mode = true; // 自动模式
extern QString strbuf;//发送缓冲区
/*阈值*/
QString EnsoilHumi;
QString Enrain;
QString Entemp;
QString Enlight;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->system_init();  //系统各组件初始化
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::system_init()
{

    //创建曲线表1
    creatChart1();
    //创建曲线表2
    creatChart2();
    //状态栏添加时间显示控件
    statusbar_init();

    //工具栏大小设置
     QSize si;
     si.setWidth(40);
     si.setHeight(40);
     ui->toolBar->setIconSize(si);
     this->setWindowIcon(QIcon(":/img/ctrl.ico"));

     ui->horizontalSlider->setRange(0,100);
//     setFixedSize(905,602); //设置固定大小
     ui->ip_edi->setText("192.168.104.14"); //当前电脑的ipv4地址
     ui->port_edi->setText("8080");
     //蓄水
     ui->progressBar->setValue(0);
     ui->spinBox->setValue(5);

    setWindowTitle("智能灌溉平台");

    //创建定时器1，定时表格更新
    timer1 = new QTimer(this);
    timer1->start(1000);// 定时器每隔1s种就执行获取表格数据的槽函数
    connect(timer1,SIGNAL(timeout()),this,SLOT(ReData_Slot()));

    //创建定时器2，定时表格更新
    timer2 = new QTimer(this);
    timer2->start(20);
    connect(timer2,SIGNAL(timeout()),this,SLOT(time_send_Slot()));

     //网络设置
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));

}

void MainWindow::statusbar_init()
{
    // 这是statusbar的相关初始化
    statusBar()->setStyleSheet("background-color : rgb(170,255,255)");//设置状态栏的颜色
    ui->statusbar->setSizeGripEnabled(false);//去掉状态栏右下角的三角

    QLabel *permanent = new QLabel(this); //创建一个新的控件显示超链接标签
    permanent->setFrameStyle(QFrame::Box | QFrame::Sunken);
    permanent->setText(
      tr("<a href=\"https://gitee.com/wangyoujie11/qt_-intelligent_irrigation_system\">gitee地址</a>"));
    permanent->setTextFormat(Qt::RichText);
    permanent->setOpenExternalLinks(true); //打开超链接
    ui->statusbar->addPermanentWidget(permanent);

    //时间显示控件
    currentTimeLabel = new QLabel(this);
    ui->statusbar->addWidget(currentTimeLabel);

    statusLabel = new QLabel;
    statusLabel->setMinimumSize(50, 20); // 设置标签最小大小
//    statusLabel->setFrameShape(QFrame::WinPanel); // 设置标签形状
//    statusLabel->setFrameShadow(QFrame::Sunken); // 设置标签阴影
    ui->statusbar->addWidget(statusLabel);
    statusLabel->setText(tr("by:wj"));
//    statusLabel->setStyleSheet("color: white");

}

void MainWindow::creatChart1()
{

    QChart *qchart = new QChart();
    //把chart放到容器里
    ui->graphicsView->setChart(qchart);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing); //设置抗锯齿
    QLineSeries *series0 = new QLineSeries;
    QLineSeries *series1 = new QLineSeries;
    QLineSeries *series2 = new QLineSeries;

    //设置名字
    series0->setName("温度");
    series1->setName("湿度");
    series2->setName("光强");

    //把线条放到chart里
    qchart->addSeries(series0);
    qchart->addSeries(series1);
    qchart->addSeries(series2);

    //创建x 坐标
    QDateTimeAxis *axisX = new QDateTimeAxis;
    //格式
    axisX->setFormat("hh:mm:ss");
    //设置竖条数量
    axisX->setTickCount(5);

    //设置坐标名称
    axisX->setTitleText("time(sec)");
    qchart->setAxisX(axisX,series0);
    qchart->setAxisX(axisX,series1);
    qchart->setAxisX(axisX,series2);

    //创建y坐标
    QValueAxis  *axisY = new QValueAxis;
    axisY->setRange(0,100);
    axisY->setTickCount(5);

    qchart->setAxisY(axisY,series0);
    qchart->setAxisY(axisY,series1);
    qchart->setAxisY(axisY,series2);

    qchart->setDropShadowEnabled(true);

    //初始化坐标
    qchart->axisX()->setMin(QDateTime::currentDateTime().addSecs(0));    //设置最大值坐标值 系统时间当前时间
    qchart->axisX()->setMax(QDateTime::currentDateTime().addSecs(5*30));  //设置最大值坐标值 系统时间后5*30秒
}

void MainWindow::creatChart2()
{
    QChart *qchart = new QChart();
    ui->graphicsView_2->setChart(qchart);
    ui->graphicsView_2->setRenderHint(QPainter::Antialiasing); //设置抗锯齿`

    //创建线条
    QLineSeries *series0 = new QLineSeries;
    QLineSeries *series1 = new QLineSeries;
    QLineSeries *series2 = new QLineSeries;

    //设置名字
    series0->setName("土壤湿度");
    series1->setName("有害气体");
    series2->setName("雨滴");

    //把线条放入chart中
    qchart->addSeries(series0);
    qchart->addSeries(series1);
    qchart->addSeries(series2);

    qchart->setDropShadowEnabled(true); //设置阴影显示

    //设置x,y的坐标
    QDateTimeAxis *axisX = new QDateTimeAxis;

    //格式
    axisX->setFormat("hh:mm:ss");
    //设置竖条数量
    axisX->setTickCount(5);

    axisX->setTitleText("time(sec)");

    qchart->setAxisX(axisX,series0);
    qchart->setAxisX(axisX,series1);
    qchart->setAxisX(axisX,series2);

    //创建y坐标
    QValueAxis *axisY = new QValueAxis;
    axisY->setRange(0,100);
    qchart->setAxisY(axisY,series0);
    qchart->setAxisY(axisY,series1);
    qchart->setAxisY(axisY,series2);

}

void MainWindow::DisplayChart1()
{
    //获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    //获取初始化表
    QChart *qchart = (QChart *)ui->graphicsView->chart();
    //获取初始化的series
    QLineSeries *series0 = (QLineSeries *)ui->graphicsView->chart()->series().at(0);
    QLineSeries *series1 = (QLineSeries *)ui->graphicsView->chart()->series().at(1);
    QLineSeries *series2 = (QLineSeries *)ui->graphicsView->chart()->series().at(2);

    series0->append(currentTime.toMSecsSinceEpoch(),temp_data); //设置表格温度的数据
    series1->append(currentTime.toMSecsSinceEpoch(),humi_data); //设置表格土壤湿度的数据
    series2->append(currentTime.toMSecsSinceEpoch(),light_data); //设置表格光照的数据

    //设置x轴显示的范围
    qchart->axisX()->setMin(QDateTime::currentDateTime().addSecs(-5*30));
    qchart->axisX()->setMax(QDateTime::currentDateTime().addSecs(5*30));


}

void MainWindow::DisplayChart2()
{

    //获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    //获取初始化表
    QChart *qchart = (QChart *)ui->graphicsView_2->chart();
    //获取初始化的series
    QLineSeries *series0 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(0);
    QLineSeries *series1 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(1);
    QLineSeries *series2 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(2);

    series0->append(currentTime.toMSecsSinceEpoch(),soil_data);
    series1->append(currentTime.toMSecsSinceEpoch(),mq2_data);
    series2->append(currentTime.toMSecsSinceEpoch(),rain_data);

    //设置x轴显示的范围
    qchart->axisX()->setMin(QDateTime::currentDateTime().addSecs(-5*30));
    qchart->axisX()->setMax(QDateTime::currentDateTime().addSecs(5*30));

}

//返回数据
void MainWindow::BackDataParsing(QString strBuf)
{
    //定义数据帧格式
    if(strBuf.startsWith("Params")){
        //表1数据
        QString str = strBuf.mid(strBuf.indexOf("temp:")+((QString)"temp:").length(),strBuf.indexOf("humi:")-strBuf.indexOf("temp:")-((QString)"temp:").length()-1);
        tcpSocket->write(str.toUtf8()); //转换字符串格式
        tcpSocket->write("->");

        QString st2 = strBuf.mid(strBuf.indexOf("humi:")+((QString)"humi:").length(),strBuf.indexOf("light:")-strBuf.indexOf("humi:")-((QString)"humi:").length()-1);
        tcpSocket->write(st2.toUtf8());
        tcpSocket->write("->");

        QString st3 = strBuf.mid(strBuf.indexOf("light:")+((QString)"light:").length(),strBuf.indexOf("soil:")-strBuf.indexOf("light:")-((QString)"light:").length()-1);
        tcpSocket->write(st3.toUtf8());
        tcpSocket->write("->");

        //表二数据
        QString st4 = strBuf.mid(strBuf.indexOf("soil:")+((QString)"soil:").length(),strBuf.indexOf("mq2:")-strBuf.indexOf("soil:")-((QString)"soil:").length()-1);
        tcpSocket->write(st4.toUtf8());
        tcpSocket->write("->");

        QString st5 = strBuf.mid(strBuf.indexOf("mq2:")+((QString)"mq2:").length(),strBuf.indexOf("rain:")-strBuf.indexOf("mq2:")-((QString)"mq2:").length()-1);
        tcpSocket->write(st5.toUtf8());
        tcpSocket->write("->");

        QString st6 = strBuf.mid(strBuf.indexOf("rain:")+((QString)"rain:").length(),strBuf.indexOf("}")-strBuf.indexOf("rain:")-((QString)"rain:").length()-1);
        tcpSocket->write(st6.toUtf8());

        //更新至表格
         temp_data = str.toFloat(); //转化为浮点类型
         humi_data = st2.toFloat();
         light_data = st3.toFloat();

         soil_data = st4.toFloat();
         mq2_data = st5.toFloat();
         rain_data = st6.toFloat();

         //送入标签
         ToUpdata_Lab(str,st2,st3,st4,st5,st6);

         //送入数据库
          data_base->UpdataToDataBase(str,st2,st3,st4,st5,st6);
    }
    else{
        QMessageBox::warning(NULL,"waring","数据帧格式有误",QMessageBox::Yes);
    }
}

void MainWindow::ToUpdata_Lab(QString Stemp, QString Shumi, QString Slight, QString Ssoil, QString Smq2, QString Srain)
{
    ui->temp_la->setText(Stemp+"%");
    ui->humi_la->setText(Shumi+"%");
    ui->light_la->setText(Slight+"%");

    ui->soil_la->setText(Ssoil+"%");
    ui->mq2_la->setText(Smq2+"%");
    ui->rain_la->setText(Srain+"%");
}


void MainWindow::ReData_Slot()
{
    static int timer = 0;

    //时间更新
    QFont font("Microsoft YaHei",20,50);
    QDateTime current_time  = QDateTime::currentDateTime(); //获取当前系统的时间
    QString timestr = current_time.toString( "yyyy年MM月dd日 hh:mm:ss"); //设置显示的格式
    currentTimeLabel->setText(timestr); //设置label的文本内容为时间

    //图表更新
    DisplayChart1();
    DisplayChart2();

    //继电器控制抽水
    if(relaySw){
        timer++;
        int boVal = ui->spinBox->value(); //设定总共抽水的时间
        ui->progressBar->setValue((timer*100)/boVal);
       //超时后自动关闭
        if(timer>=boVal){
            timer=0;
            relaySw=false;
            ui->relay->setIcon(QIcon(":/img/relay_off.png"));
            tcpSocket->write("relay_off");
            ui->progressBar->setValue(100);
        }
    }
    else{
        timer=0;
        ui->progressBar->setValue(0);
    }
}


// led开关
void MainWindow::on_led_triggered()
{
    static bool ledSw = false;
    ledSw = !ledSw; //状态翻转

    if(ledSw){
        ui->led->setIcon(QIcon(":/img/led_on.png")); //添加资源中的图片
        tcpSocket->write("led_on");
    }
    else{
        ui->led->setIcon(QIcon(":/img/led_off.png")); //添加资源中的图片
        tcpSocket->write("led_off");
    }
}

// 继电器开关
void MainWindow::on_relay_triggered()
{
    relaySw = !relaySw;
    if(relaySw){
        ui->relay->setIcon(QIcon(":/img/relay_on.png")); //添加资源中的图片
        tcpSocket->write("relay_on");
    }
    else{
        ui->relay->setIcon(QIcon(":/img/relay_off.png")); //添加资源中的图片
        tcpSocket->write("relay_off");
    }

}

void MainWindow::on_open_wifi_triggered()
{

    flag_Sw=!flag_Sw;

    if(flag_Sw){
        statusLabel->setText(tr("网络成功开启----"));
        ui->wifi_l->setStyleSheet("border-image: url(:/img/wifi_on.png);");
        ui->open_wifi->setIcon(QIcon(":/img/open.png"));

        //选择主机通信
        if(Master){
            tcpServer->listen(QHostAddress::Any,ui->port_edi->text().toUInt()); //获取网络地址信息
        }
        else
        {
            tcpSocket->connectToHost(ui->ip_edi->text(),ui->port_edi->text().toUInt());
            connect(tcpSocket,SIGNAL(connected()),this,SLOT(connetced_Slot()));
        }

    }

    else{
        statusLabel->setText(tr("网络已关闭----"));
        ui->wifi_l->setStyleSheet("border-image: url(:/img/wifi_off.png);");
        ui->open_wifi->setIcon(QIcon(":/img/close.png"));
        tcpServer->close();
        tcpSocket->close();
    }

}

void MainWindow::on_set_yu_bt_clicked()
{
    QString sendThrshold;

    sendThrshold =  EnsoilHumi + " " + "soil:" + ui->soil_yu_la->text()+";"+
                    Enrain     + " " + "rain:"+ ui->rain_yu_la->text()+";"+
                    Entemp     + " " + "temp:"+ ui->temp_yu_la->text()+";"+
                    Enlight    + " " + "light:"+ui->light_yu_la->text();

    qDebug() <<"发送阈值";
    tcpSocket->write(sendThrshold.toLocal8Bit());
}

void MainWindow::on_clear_yu_bt_clicked()
{
    ui->checkBox_rain->setChecked(false);
    ui->checkBox_soil->setChecked(false);
    ui->checkBox_temp->setChecked(false);
    ui->checkBox_light->setChecked(false);

    ui->soil_yu_la->clear();
    ui->temp_yu_la->clear();
    ui->rain_yu_la->clear();
    ui->light_yu_la->clear();

    qDebug() <<"清除阈值显示区";
}

void MainWindow::on_checkBox_soil_stateChanged(int arg1)
{
    qDebug()<<arg1;
    if(arg1==2)
        EnsoilHumi="enable";
    else
        EnsoilHumi="disable";
}

void MainWindow::on_checkBox_rain_stateChanged(int arg1)
{
    qDebug()<<arg1;

    if(arg1==2)
         Enrain="enable";
    else
         Enrain="disable";
}

void MainWindow::on_checkBox_temp_stateChanged(int arg1)
{
    qDebug()<<arg1;

    if(arg1==2)
         Entemp="enable";
    else
         Entemp="disable";
}

void MainWindow::on_checkBox_light_stateChanged(int arg1)
{
    qDebug()<<arg1;
    if(arg1==2)
         Enlight="enable";
    else
         Enlight="disable";
}
/*=======================================网络通信=========================================*/

void MainWindow::newConnection_Slot()
{
    tcpSocket = tcpServer->nextPendingConnection();//得到通信的套接字对象
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
    connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected_Slot()));
    ui->connect_l->setStyleSheet("border-image: url(:/img/connect.png)");
}

void MainWindow::readyRead_Slot()
{
    QByteArray receiveDate;
    QTextCodec *tc = QTextCodec::codecForName("GBK");//设置编码格式

    while(!tcpSocket->atEnd()){
        receiveDate = tcpSocket->readAll(); //读取全部的数据
    }

    if(!receiveDate.isEmpty()){
        QString strBuff = tc->toUnicode(receiveDate);    //编码转换,必须转换编码，否则乱码
        //传入调试界面
        deb->DisplayData(strBuff);
        // 解析数据
        BackDataParsing(strBuff);
    }
    receiveDate.clear();
}

void MainWindow::disconnected_Slot()
{
    tcpSocket->close();
    ui->connect_l->setStyleSheet("border-image: url(:/img/discon.png)");
}

void MainWindow::connected_Slot()
{
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
    ui->connect_l->setStyleSheet("border-image: url(:/img/connect.png)");
    connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected_Slot()));
}



/*=======================================调试窗口=========================================*/

//打开调试窗口
void MainWindow::on_debb_triggered()
{
    deb->show();
}

//发送标志位
void MainWindow::test(QString buf){
    flag_Send=1;
//    tcpSocket->write(buf.toLocal8Bit().data());
    qDebug()<<"返回的数据是:"+buf;
}

void MainWindow::time_send_Slot()
{
    if(flag_Send==1){
        flag_Send=0;
        tcpSocket->write(strbuf.toLocal8Bit().data());
    }
}

void MainWindow::on_auto_hand_triggered()
{
    run_mode=!run_mode;
    if(run_mode){
      ui->auto_hand->setIcon(QIcon(":/img/auto.png"));
      tcpSocket->write("auto_mode");
    }
    else{
        //开启手动模式
        ui->auto_hand->setIcon(QIcon(":/img/hand.png"));
        tcpSocket->write("hand_mode");
    }
}

void MainWindow::on_exit_triggered()
{
    this->close();
}

void MainWindow::on_charts1_big_clicked()
{
    ui->graphicsView->chart()->zoom(1.2);//放大1.2倍
}

void MainWindow::on_charts1_small_clicked()
{
    ui->graphicsView->chart()->zoom(0.8);//放大1.2倍
}

void MainWindow::on_charts1_rest_clicked()
{
    ui->graphicsView->chart()->zoomReset();
}


void MainWindow::on_charts1_big_2_clicked()
{
    ui->graphicsView_2->chart()->zoom(1.2);//放大1.2倍
}

void MainWindow::on_charts1_small_2_clicked()
{
    ui->graphicsView_2->chart()->zoom(0.8);//放大1.2倍
}

void MainWindow::on_charts1_rest_2_clicked()
{
    ui->graphicsView_2->chart()->zoomReset();
}

void MainWindow::on_charts1_clear_1_clicked()
{
    QLineSeries *series0 = (QLineSeries *)ui->graphicsView->chart()->series().at(0);
    QLineSeries *series1 = (QLineSeries *)ui->graphicsView->chart()->series().at(1);
    QLineSeries *series2 = (QLineSeries *)ui->graphicsView->chart()->series().at(2);

    series0->clear();
    series1->clear();
    series2->clear();
}

void MainWindow::on_charts1_clear_2_clicked()
{
    QLineSeries *series0 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(0);
    QLineSeries *series1 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(1);
    QLineSeries *series2 = (QLineSeries *)ui->graphicsView_2->chart()->series().at(2);

    series0->clear();
    series1->clear();
    series2->clear();
}

//客户端/服务器切换
void MainWindow::on_sermode_clicked()
{
    if(!flag_Sw){//判断网络是否开启
        tcpServer->close();
        tcpSocket->close();
        // 客户机
        if(Master){
            Master=false;
            ui->sermode_l->setText("客户机模式");
            ui->sermode->setStyleSheet("border-image:url(:/img/client.png);");
        }
        else{
            Master=true;
            ui->sermode_l->setText("主机模式");
            ui->sermode->setStyleSheet("border-image:url(:/img/server.png);");
        }
    }
    else{
        QMessageBox::critical(NULL,"提示","请先关闭网络，再切换模式类型",QMessageBox::Yes);
    }
}

//设置光强
void MainWindow::on_set_light_bt_clicked()
{
    tcpSocket->write(("Pwm:"+QString::number(light_pwm)).toLocal8Bit());
}
//滑动改变光强
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
     ui->setlightNumla->setNum(value);
     light_pwm = value;
}

/*=======================================数据库窗口=========================================*/
void MainWindow::on_data_triggered()
{
    data_base->show();
}

void MainWindow::on_info_triggered()
{
    info_widget->show();
    qDebug()<<"提示窗口打开";
}
